/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.db;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.db.cfg.Configuration;
import com.edi.db.cfg.Environment;
import com.edi.db.connection.ConnectionProvider;
import com.edi.db.connection.ConnectionProviderFactory;
import com.edi.db.dialect.Dialect;
import com.edi.exceptions.EdiException;
import com.edi.util.PropertiesHelper;

/**
 * session 工厂
 * 
 */
public class SessionFactory {
	private static final Log log = LogFactory.getLog(SessionFactory.class);
	private ConnectionProvider connectionprovider;
	private Dialect dialect;
	private Configuration cfg;

	public SessionFactory(Configuration cfg) {
		this.cfg = cfg;
		try {
			connectionprovider = ConnectionProviderFactory
					.newConnectionProvider(cfg);
			dialect = Dialect.instantiateDialect(PropertiesHelper
					.getDialectClass(cfg.getProperty(Environment.DIALECT)));
			/**
			 * 判断方言中是否处理大小写
			 */
			if (StringUtils.equalsIgnoreCase(cfg
					.getProperty(Environment.DIALECT_IGNORECASE),
					EdiDb.DIALECT_IGNORECASE_FALSE))
				dialect.setIgnoreCase(false);
		} catch (Exception e) {
			log.error("构造 SessionFactory 发生异常！" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 打开session
	 * 
	 * @return
	 */
	public Session openSession() {
		Session session = null;
		try {
			Connection c = connectionprovider.getConnection();
			return new SessionImpl(c, dialect);
		} catch (SQLException e) {
			log.error(new EdiException("打开session发生异常", e).getMessage()
					+ ";Porvider : " + connectionprovider.getClass().getName()
					+ ";url : " + connectionprovider.getUrl());
			e.printStackTrace();
		}
		return session;
	}

	/**
	 * 关闭所有数据库连接 销毁工厂
	 */
	public void close() {
		try {
			connectionprovider.close();
			dialect = null;
		} catch (Exception e) {
			log.error("关闭session工厂出现异常");
			e.printStackTrace();
		}
	}

	public Configuration getCfg() {
		return this.cfg;
	}

}
